import os
import subprocess
import uuid

def execute_cpp_code(code):
    # 生成唯一的文件名
    code_filename = f"{uuid.uuid4()}.cpp"
    executable_filename = f"{uuid.uuid4()}"

    # 保存代码到文件
    with open(code_filename, 'w') as code_file:
        code_file.write(code)

    try:
        # 使用 Docker 编译 C++ 代码
        compile_command = f"sudo docker run  -v {os.getcwd()}:/sandbox cpp-sandbox g++ -o /sandbox/{executable_filename} /sandbox/{code_filename}"
        compile_result = subprocess.run(compile_command, shell=True, capture_output=True, text=True)

        if compile_result.returncode != 0:
            return {'status': 'compile_error', 'output': compile_result.stderr}

        # 使用 Docker 运行编译好的可执行文件
        run_command = f"sudo docker run --rm -v {os.getcwd()}:/sandbox cpp-sandbox /sandbox/{executable_filename}"
        run_result = subprocess.run(run_command, shell=True, capture_output=True, text=True, timeout=5)

        return {'status': 'success', 'output': run_result.stdout, 'error': run_result.stderr}
    except subprocess.TimeoutExpired:
        return {'status': 'timeout', 'output': 'Execution time exceeded'}
    except Exception as e:
        return {'status': 'error', 'output': str(e)}
    finally:
        # 清理生成的文件
        if os.path.exists(code_filename):
            os.remove(code_filename)
        if os.path.exists(executable_filename):
            os.remove(executable_filename)

# 示例代码
code = """
#include <iostream>
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
"""

result = execute_cpp_code(code)
print(result)
